package com.haochen.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: zhangquancheng
 * @Description: 全局过滤器
 * @Date: 2023/3/24 1:46 上午
 */

@Order(-1) ////order值越小，过滤器优先级越高，执行顺序越靠前
@Component
@Slf4j
public class AuthorizeGlobalFilterFactory implements GlobalFilter {
    private static final String AUTHORIZE_TOKEN = "token";


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        HttpHeaders headers = request.getHeaders();
        //从请求头中获取token
        String token = headers.getFirst(AUTHORIZE_TOKEN);
        if (token == null) {
            //从请求头参数中获取token
            token = request.getQueryParams().getFirst(AUTHORIZE_TOKEN);
        }

        ServerHttpResponse response = exchange.getResponse();
        //如果token为空，直接返回401，未授权
        if (StringUtils.isEmpty(token)) {
            try {
                //2.设置响应头类型
                response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                //处理完成，直接拦截，不再进行下去
                DataBufferFactory bufferFactory = response.bufferFactory();
                ObjectMapper objectMapper = new ObjectMapper();
                Map<Integer, String> result = new HashMap<Integer, String>(1);
                result.put(HttpStatus.UNAUTHORIZED.value(),"无权限访问");
                DataBuffer wrap = bufferFactory.wrap(objectMapper.writeValueAsBytes( result ));
                return response.writeWith(Mono.fromSupplier(() -> wrap));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return response.setComplete();
        }
        /**
         * todo chain.filter(exchange) 之前的都是过滤器的前置处理
         *
         * chain.filter().then(
         *  过滤器的后置处理...........
         * )
         */
        //授权正常，继续下一个过滤器链的调用
        return chain.filter(exchange);
    }
}
